<template>
  <div class="scene-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>AI场景管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddRootScene">
              <el-icon><Plus /></el-icon>
              添加根场景
            </el-button>
            <el-button @click="refreshSceneTree">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.scene_name"
              placeholder="搜索场景名称"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="searchForm.scene_status"
              placeholder="场景状态"
              clearable
              @change="handleSearch"
            >
              <el-option label="激活" value="active" />
              <el-option label="非激活" value="inactive" />
              <el-option label="待审核" value="pending_review" />
              <el-option label="已归档" value="archived" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-input
              v-model="searchForm.creator"
              placeholder="创建人"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="4">
            <el-input-number
              v-model="searchForm.max_depth"
              placeholder="最大深度"
              :min="0"
              :max="10"
              @change="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-switch
              v-model="searchForm.include_children"
              active-text="包含子节点"
              @change="handleSearch"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 场景树展示区域 -->
      <div class="tree-section">
        <el-tree
          ref="sceneTreeRef"
          :data="sceneTreeData"
          :props="treeProps"
          node-key="scene_id"
          :expand-on-click-node="false"
          :default-expand-all="false"
          :render-content="renderTreeNode"
          draggable
          @node-drop="handleNodeDrop"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
        />
      </div>

      <!-- 统计信息 -->
      <div class="stats-section" v-if="sceneStats">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-statistic title="总场景数" :value="sceneStats.total_count" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="最大深度" :value="sceneStats.max_depth" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="根节点数" :value="sceneStats.root_nodes?.length || 0" />
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 场景详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="sceneFormRef"
        :model="sceneForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="场景名称" prop="scene_name">
          <el-input v-model="sceneForm.scene_name" placeholder="请输入场景名称" />
        </el-form-item>
        
        <el-form-item label="场景描述" prop="description">
          <el-input
            v-model="sceneForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入场景描述"
          />
        </el-form-item>

        <el-form-item label="父场景" prop="parent_id" v-if="!isRootScene">
          <el-tree-select
            v-model="sceneForm.parent_id"
            :data="parentSelectData"
            :props="{ label: 'scene_name', value: 'scene_id' }"
            placeholder="选择父场景"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="排序序号" prop="sort_order">
          <el-input-number
            v-model="sceneForm.sort_order"
            :min="0"
            :max="999"
            placeholder="排序序号"
          />
        </el-form-item>

        <el-form-item label="场景状态" prop="scene_status">
          <el-radio-group v-model="sceneForm.scene_status">
            <el-radio label="active">激活</el-radio>
            <el-radio label="inactive">非激活</el-radio>
            <el-radio label="pending_review">待审核</el-radio>
            <el-radio label="archived">已归档</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="创建人" prop="creator" v-if="isCreateMode">
          <el-input v-model="sceneForm.creator" placeholder="请输入创建人" />
        </el-form-item>

        <el-form-item label="修改人" prop="modifier" v-if="!isCreateMode">
          <el-input v-model="sceneForm.modifier" placeholder="请输入修改人" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isCreateMode ? '创建' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 场景详情查看对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="场景详情"
      width="800px"
    >
      <div v-if="currentScene" class="scene-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="场景ID">
            {{ currentScene.scene_id }}
          </el-descriptions-item>
          <el-descriptions-item label="场景名称">
            {{ currentScene.scene_name }}
          </el-descriptions-item>
          <el-descriptions-item label="节点层级">
            <el-tag>第 {{ currentScene.node_level }} 级</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="场景状态">
            <el-tag :type="getStatusType(currentScene.scene_status)">
              {{ getStatusText(currentScene.scene_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="节点路径" :span="2">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="item in scenePath" :key="item.scene_id">
                {{ item.scene_name }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </el-descriptions-item>
          <el-descriptions-item label="场景描述" :span="2">
            {{ currentScene.description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="排序序号">
            {{ currentScene.sort_order }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ currentScene.creator }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentScene.create_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="修改人">
            {{ currentScene.modifier || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="修改时间" :span="2">
            {{ currentScene.modify_time ? formatDateTime(currentScene.modify_time) : '暂无' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 子场景列表 -->
        <div v-if="currentScene.children && currentScene.children.length > 0" class="children-section">
          <h4>子场景列表</h4>
          <el-table :data="currentScene.children" style="width: 100%">
            <el-table-column prop="scene_name" label="场景名称" />
            <el-table-column prop="node_level" label="层级" width="80" />
            <el-table-column prop="scene_status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.scene_status)">
                  {{ getStatusText(row.scene_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sort_order" label="排序" width="80" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElButton, ElIcon, ElTag } from 'element-plus'
import { Plus, Refresh, Search, Edit, Delete, View, FolderAdd } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { sceneApi, type AIWebScene, type SceneTreeResponse, type SearchForm } from '../../api/scene'

// 类型定义已在API文件中定义

// 响应式数据
const sceneTreeData = ref<AIWebScene[]>([])
const sceneStats = ref<SceneTreeResponse | null>(null)
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitLoading = ref(false)
const currentScene = ref<AIWebScene | null>(null)
const scenePath = ref<AIWebScene[]>([])
const isCreateMode = ref(true)
const isRootScene = ref(false)

// 表单相关
const sceneFormRef = ref<FormInstance>()
const sceneTreeRef = ref()

const searchForm = reactive<SearchForm>({
  scene_name: '',
  scene_status: '',
  creator: '',
  include_children: true,
  max_depth: undefined
})

const sceneForm = reactive({
  scene_name: '',
  description: '',
  parent_id: '',
  sort_order: 0,
  scene_status: 'active',
  creator: '',
  modifier: '',
  version: 0
})

// 表单验证规则
const formRules: FormRules = {
  scene_name: [
    { required: true, message: '请输入场景名称', trigger: 'blur' },
    { min: 1, max: 100, message: '场景名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  creator: [
    { required: true, message: '请输入创建人', trigger: 'blur' }
  ],
  modifier: [
    { required: true, message: '请输入修改人', trigger: 'blur' }
  ]
}

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'scene_name'
}

// 计算属性
const dialogTitle = computed(() => {
  if (isCreateMode.value) {
    return isRootScene.value ? '创建根场景' : '创建子场景'
  }
  return '编辑场景'
})

const parentSelectData = computed(() => {
  // 将树形数据转换为选择器数据，排除当前编辑的节点
  const convertToSelectData = (nodes: AIWebScene[]): any[] => {
    return nodes.map(node => ({
      scene_id: node.scene_id,
      scene_name: node.scene_name,
      children: node.children ? convertToSelectData(node.children) : []
    }))
  }
  return convertToSelectData(sceneTreeData.value)
})

// 使用导入的API

// 方法函数
const loadSceneTree = async () => {
  try {
    loading.value = true
    const result = await sceneApi.getSceneTree(searchForm)
    sceneTreeData.value = result.root_nodes
    sceneStats.value = result
  } catch (error) {
    ElMessage.error('加载场景树失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  loadSceneTree()
}

const refreshSceneTree = () => {
  loadSceneTree()
}

const handleAddRootScene = () => {
  isCreateMode.value = true
  isRootScene.value = true
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (node: AIWebScene) => {
  isCreateMode.value = true
  isRootScene.value = false
  resetForm()
  sceneForm.parent_id = node.scene_id
  dialogVisible.value = true
}

const handleEdit = async (node: AIWebScene) => {
  isCreateMode.value = false
  isRootScene.value = !node.parent_id
  
  // 填充表单数据
  Object.assign(sceneForm, {
    scene_name: node.scene_name,
    description: node.description || '',
    parent_id: node.parent_id || '',
    sort_order: node.sort_order,
    scene_status: node.scene_status,
    creator: node.creator,
    modifier: '',
    version: node.version
  })
  
  currentScene.value = node
  dialogVisible.value = true
}

const handleView = async (node: AIWebScene) => {
  currentScene.value = node
  
  // 获取场景路径
  try {
    scenePath.value = await sceneApi.getScenePath(node.scene_id)
  } catch (error) {
    ElMessage.error('获取场景路径失败')
  }
  
  detailDialogVisible.value = true
}

const handleDelete = async (node: AIWebScene) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除场景 "${node.scene_name}" 及其所有子场景吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await sceneApi.deleteScene(node.scene_id)
    ElMessage.success('删除成功')
    await loadSceneTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error as Error).message)
    }
  }
}

const handleSubmit = async () => {
  if (!sceneFormRef.value) return
  
  try {
    await sceneFormRef.value.validate()
    submitLoading.value = true
    
    if (isCreateMode.value) {
      const createData = {
        scene_name: sceneForm.scene_name,
        description: sceneForm.description,
        parent_id: isRootScene.value ? undefined : sceneForm.parent_id,
        sort_order: sceneForm.sort_order,
        scene_status: sceneForm.scene_status,
        creator: sceneForm.creator
      }
      await sceneApi.createScene(createData)
      ElMessage.success('创建成功')
    } else {
      const updateData = {
        scene_name: sceneForm.scene_name,
        description: sceneForm.description,
        sort_order: sceneForm.sort_order,
        scene_status: sceneForm.scene_status,
        modifier: sceneForm.modifier,
        version: sceneForm.version
      }
      await sceneApi.updateScene(currentScene.value!.scene_id, updateData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    await loadSceneTree()
  } catch (error) {
    ElMessage.error((isCreateMode.value ? '创建' : '更新') + '失败: ' + (error as Error).message)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(sceneForm, {
    scene_name: '',
    description: '',
    parent_id: '',
    sort_order: 0,
    scene_status: 'active',
    creator: '',
    modifier: '',
    version: 0
  })
  sceneFormRef.value?.clearValidate()
}

// 树形节点拖拽
const allowDrop = (draggingNode: any, dropNode: any, type: string) => {
  // 不允许拖拽到自己的子节点中
  return type !== 'inner' || !isDescendant(draggingNode.data, dropNode.data)
}

const allowDrag = (_draggingNode: any) => {
  // 所有节点都允许拖拽
  return true
}

const isDescendant = (ancestor: AIWebScene, node: AIWebScene): boolean => {
  if (!ancestor.children) return false
  return ancestor.children.some(child => 
    child.scene_id === node.scene_id || isDescendant(child, node)
  )
}

const handleNodeDrop = async (draggingNode: any, dropNode: any, dropType: string) => {
  try {
    const dragData = draggingNode.data
    let newParentId: string | undefined
    
    if (dropType === 'inner') {
      newParentId = dropNode.data.scene_id
    } else {
      newParentId = dropNode.data.parent_id
    }
    
    await sceneApi.moveScene(dragData.scene_id, newParentId)
    ElMessage.success('移动成功')
    await loadSceneTree()
  } catch (error) {
    ElMessage.error('移动失败: ' + (error as Error).message)
    await loadSceneTree() // 重新加载以恢复原始状态
  }
}

// 树形节点渲染
const renderTreeNode = (h: any, { data }: { node: any, data: AIWebScene }) => {
  return h('div', { class: 'tree-node' }, [
    h('div', { class: 'node-content' }, [
      h('span', { class: 'node-label' }, [
        h('el-tag', { 
          size: 'small', 
          type: getStatusType(data.scene_status),
          style: 'margin-right: 8px'
        }, getStatusText(data.scene_status)),
        h('span', { class: 'scene-name' }, data.scene_name),
        h('el-tag', { 
          size: 'small', 
          type: 'info',
          style: 'margin-left: 8px'
        }, `L${data.node_level}`)
      ])
    ]),
    h('div', { class: 'node-actions' }, [
      h(ElButton, {
        size: 'small',
        type: 'primary',
        icon: View,
        circle: true,
        onClick: (e: Event) => {
          e.stopPropagation()
          handleView(data)
        }
      }),
      h(ElButton, {
        size: 'small',
        type: 'success',
        icon: FolderAdd,
        circle: true,
        onClick: (e: Event) => {
          e.stopPropagation()
          handleAddChild(data)
        }
      }),
      h(ElButton, {
        size: 'small',
        type: 'warning',
        icon: Edit,
        circle: true,
        onClick: (e: Event) => {
          e.stopPropagation()
          handleEdit(data)
        }
      }),
      h(ElButton, {
        size: 'small',
        type: 'danger',
        icon: Delete,
        circle: true,
        onClick: (e: Event) => {
          e.stopPropagation()
          handleDelete(data)
        }
      })
    ])
  ])
}

// 工具函数
const getStatusType = (status: string): 'success' | 'info' | 'warning' | 'danger' => {
  const statusMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    active: 'success',
    inactive: 'info',
    pending_review: 'warning',
    archived: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '激活',
    inactive: '非激活',
    pending_review: '待审核',
    archived: '已归档'
  }
  return statusMap[status] || status
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadSceneTree()
})
</script>

<style scoped>
.scene-management {
  height: 100%;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.tree-section {
  margin-bottom: 20px;
  min-height: 400px;
}

.stats-section {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.node-content {
  flex: 1;
}

.node-label {
  display: flex;
  align-items: center;
}

.scene-name {
  font-weight: 500;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.scene-detail {
  max-height: 600px;
  overflow-y: auto;
}

.children-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.children-section h4 {
  margin-bottom: 16px;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

:deep(.el-tree-node__expand-icon) {
  padding: 6px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style> 